package code._16reflect._07add;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader{
    String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //获取字节码文件数据
        byte[] data =null;
        Class<?> aClass=null;
        try {
            data=getData();
            aClass = defineClass(name, data, 0, data.length);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return aClass;
    }

    private byte[] getData() throws IOException{
        File file = new File(classPath);
        InputStream in = new FileInputStream(file);
        byte[] bytes=new byte[((int) file.length())];
        in.read(bytes);
        return bytes;
    }
}
